package com.growthsee.rider.wrapper;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.growthsee.common.constant.Constants;
import com.growthsee.common.core.domain.entity.SysDictData;
import com.growthsee.common.core.redis.RedisCache;
import com.growthsee.common.utils.DateUtils;
import com.growthsee.common.utils.SecurityUtils;
import com.growthsee.common.utils.StringUtils;
import com.growthsee.rider.domain.RiderCompany;
import com.growthsee.rider.domain.RiderInfo;
import com.growthsee.rider.domain.RiderInfoCar;
import com.growthsee.rider.domain.RiderPushLog;
import com.growthsee.rider.domain.dto.RiderInfoDto;
import com.growthsee.rider.domain.view.RiderInfoView;
import com.growthsee.rider.enumeration.OperateEnum;
import com.growthsee.rider.enumeration.YesNoEnum;
import com.growthsee.rider.mapper.RiderInfoMapper;
import com.growthsee.rider.param.BaiduResult;
import com.growthsee.rider.param.BaiduToken;
import com.growthsee.rider.param.ReqParam;
import com.growthsee.rider.param.ResData;
import com.growthsee.rider.service.RiderCompanyService;
import com.growthsee.rider.service.RiderInfoService;
import com.growthsee.rider.service.RiderPushLogService;
import com.growthsee.rider.utils.ApplicationContexts;
import com.growthsee.rider.utils.BasicPathUtil;
import com.growthsee.rider.utils.OkhttpUtil;
import com.growthsee.rider.utils.SHA256Utils;
import com.growthsee.rider.utils.SM.SM2Utils;
import com.growthsee.system.mapper.SysDictDataMapper;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ycj
 * @Description: 评价活动视图包装类
 * @date 2020/05/24
 **/
public class RiderWrapper {


    public static RiderWrapper builder() {
        return new RiderWrapper();
    }



    public String check(RiderInfo riderInfo){
        RiderInfoMapper riderInfoMapper = ApplicationContexts.getBean(RiderInfoMapper.class);
        LambdaQueryWrapper<RiderInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(RiderInfo::getOpenId, riderInfo.getOpenId());
        queryWrapper.eq(RiderInfo::getDeleted, YesNoEnum.NO.getValue());
        Integer integer = riderInfoMapper.selectCount(queryWrapper);
        if(integer>0){
            return "用户已注册";
        }else return "";
    }
    //组装请求数据
    public String pushData(RiderInfo riderInfo) {
        RiderCompanyService riderCompanyService = ApplicationContexts.getBean(RiderCompanyService.class);
        RiderCompany riderCompany = riderCompanyService.getById(riderInfo.getPlatformCompanyId());
        //组装reqData数据
        JSONObject reqData = new JSONObject();
        reqData.put("mobileNo", riderInfo.getMobilePhone());
        reqData.put("userName", riderInfo.getName());
        reqData.put("idCardNo", riderInfo.getIdCard());
        reqData.put("companyName", riderCompany.getName());
        reqData.put("comAddr", riderCompany.getAddress());
        reqData.put("regDate", DateUtils.parseDateToStr("yyyyMMdd", riderInfo.getUpdateTime()));
        reqData.put("userStat", riderInfo.getStatus());
        reqData.put("bindStat", riderInfo.getRegisterStatus());
        RiderPushLog riderPushLog = new RiderPushLog();
        riderPushLog.setRiderId(riderInfo.getId());
        riderPushLog.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        riderPushLog.setCreateTime(new Date());
        RiderPushLogService riderPushLogService = ApplicationContexts.getBean(RiderPushLogService.class);
        try {
            ResData resData = send(reqData, riderInfo.getId());//发送请求
            riderPushLog.setStatus(resData.getCode());
            riderPushLog.setJsonData(ObjectUtils.isEmpty(resData)?"请求超时":resData.getReqData());
            riderPushLog.setMsg(resData.getMsg());
            riderPushLogService.save(riderPushLog);
            if(resData.getCode()!=200){
                return resData.getMsg();
            }
        }catch (Exception e){
            riderPushLog.setStatus(500);
            riderPushLog.setMsg(e.getMessage());
            riderPushLogService.save(riderPushLog);
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 推送数据
     * @param reqData
     * @param bussSeqNo
     * @return
     */
    public ResData send(JSONObject reqData,String bussSeqNo){
        try {
            String chanelId = BasicPathUtil.getChannelId();
            String reqTime = DateUtils.parseDateToStr("YYYYMMDDHHmmssSSS", new Date());
            String reqUrl = BasicPathUtil.getUrl();
            String pubk=BasicPathUtil.getReqPubk();
            String reqDataStr = SM2Utils.encrypt(pubk, reqData.toString());
            //SHA256加密请求体
            StringBuffer sb = new StringBuffer(bussSeqNo).append(reqTime).append(chanelId).append(reqDataStr);
            String sign = SHA256Utils.sha256(sb.toString());
            ReqParam build = ReqParam.builder()
                    .bussSeqNo(bussSeqNo)
                    .channelId(chanelId)
                    .reqTime(reqTime)
                    .sign(sign)
                    .reqData(reqDataStr)
                    .build();
            //发送请求
            String jsonObj = JSONObject.toJSONString(build);
            String result =OkhttpUtil.doPostHttpRequest(reqUrl,jsonObj);
            System.out.println(result);
            ResData resData = JSONArray.parseObject(result, ResData.class);
            resData.setReqData(jsonObj);
            return resData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 赋值属性
     * @param records
     */
    public void propertyHandler(List<RiderInfoDto> records) {
        if(CollectionUtils.isEmpty(records))return;
        List<String>platformCompanyIds = records.stream().map(s->s.getPlatformCompanyId()).distinct().collect(Collectors.toList());
        List<String>agentCompanyIds = records.stream().map(s->s.getAgentCompanyId()).distinct().collect(Collectors.toList());
        List<String>riderIds = records.stream().map(s->s.getId()).distinct().collect(Collectors.toList());
        RiderCompanyService riderCompanyService = ApplicationContexts.getBean(RiderCompanyService.class);
        List<RiderCompany>platformCompanys=null;
        List<RiderCompany>agentCompanys=null;
        if(CollectionUtils.isNotEmpty(platformCompanyIds)){
            platformCompanys= riderCompanyService.list(Wrappers.<RiderCompany>lambdaQuery().in(RiderCompany::getId,platformCompanyIds));
        }
        if(CollectionUtils.isNotEmpty(agentCompanyIds)){
            agentCompanys= riderCompanyService.list(Wrappers.<RiderCompany>lambdaQuery().in(RiderCompany::getId,agentCompanyIds));
        }
        SysDictDataMapper sysDictDataMapper = ApplicationContexts.getBean(SysDictDataMapper.class);

        List<SysDictData> userSexList = sysDictDataMapper.selectDictDataByType("sys_user_sex");//性别
        List<SysDictData> zhmzList = sysDictDataMapper.selectDictDataByType("zhmz");//名族
        List<SysDictData> riderTypeList = sysDictDataMapper.selectDictDataByType("rider_type");//骑手类型
        RiderPushLogService pushLogService = ApplicationContexts.getBean(RiderPushLogService.class);
        List<RiderPushLog>riderPushLogs = pushLogService.list(Wrappers.<RiderPushLog>lambdaQuery().in(RiderPushLog::getRiderId,riderIds).ne(RiderPushLog::getStatus,500));
        for(RiderInfoDto v:records){
            if(CollectionUtils.isNotEmpty(userSexList) && ObjectUtils.isNotEmpty(v.getSex())){
                SysDictData userSex = userSexList.stream().filter(s-> StringUtils.equals(s.getDictValue(),v.getSex().toString())).findFirst().orElse(null);
                if(ObjectUtils.isNotEmpty(userSex)){
                    v.setSexName(userSex.getDictLabel());
                }
            }
            if(CollectionUtils.isNotEmpty(zhmzList) && ObjectUtils.isNotEmpty(v.getNational())){
                SysDictData zhmz = zhmzList.stream().filter(s-> StringUtils.equals(s.getDictValue(),v.getNational())).findFirst().orElse(null);
                if(ObjectUtils.isNotEmpty(zhmz)){
                    v.setNationalName(zhmz.getDictLabel());
                }
            }
            if(CollectionUtils.isNotEmpty(riderTypeList) && ObjectUtils.isNotEmpty(v.getRiderType())){
                SysDictData riderType = riderTypeList.stream().filter(s-> StringUtils.equals(s.getDictValue(),v.getRiderType().toString())).findFirst().orElse(null);
                if(ObjectUtils.isNotEmpty(riderType)){
                    v.setRiderTypeName(riderType.getDictLabel());
                }
            }
            if(CollectionUtils.isNotEmpty(platformCompanys)){
                RiderCompany platformCompany = platformCompanys.stream().filter(s-> StringUtils.equals(s.getId(),v.getPlatformCompanyId())).findFirst().orElse(null);
                if(ObjectUtils.isNotEmpty(platformCompany)){
                    v.setPlatformCompanyName(platformCompany.getName());
                }
            }
            if(CollectionUtils.isNotEmpty(agentCompanys)){
                RiderCompany agentCompany = agentCompanys.stream().filter(s-> StringUtils.equals(s.getId(),v.getAgentCompanyId())).findFirst().orElse(null);
                if(ObjectUtils.isNotEmpty(agentCompany)){
                    v.setAgentCompanyName(agentCompany.getName());
                }
            }
            if(CollectionUtils.isNotEmpty(riderPushLogs)){
                List<RiderPushLog> mylogs = riderPushLogs.stream().filter(s-> StringUtils.equals(s.getRiderId(),v.getId())).collect(Collectors.toList());
                if(ObjectUtils.isNotEmpty(mylogs)){
                    v.setPushStatus(YesNoEnum.YES.getValue());
                }
            }
        }


    }

    /**
     * 检查验证码
     * @param riderInfo
     */
    public String checkVerificationCode(RiderInfoDto riderInfo) {
        if(StringUtils.isEmpty(riderInfo.getVerificationCode()))return"验证码不能为空";
        if(StringUtils.isEmpty(riderInfo.getUuid()))return "uuid不能为空";
        RedisCache redisCache = ApplicationContexts.getBean(RedisCache.class);
        String verifyKey = Constants.VERIFICATION_CODE_KEY + riderInfo.getUuid();
        String captcha = redisCache.getCacheObject(verifyKey);
        if(StringUtils.isEmpty(captcha))return "验证码已失效，请重新发送";
        // redisCache.deleteObject(verifyKey);
        if (!riderInfo.getVerificationCode().equalsIgnoreCase(captcha))  return "验证码填写不正确";
        return "";
    }

    //获取百度token
    private String getToken(){
        RedisCache redisCache = ApplicationContexts.getBean(RedisCache.class);
        String url="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Az6Emk3oV7fLTPpSPv6Uu1l7&client_secret=m9YeOmhjL9ZCZv15vXnkxzmx140IGRRc";
        String token = redisCache.getCacheObject(Constants.BAIDU_TOKEN);
        if(StringUtils.isEmpty(token)){
            try {
                String result = OkhttpUtil.doPostHttpRequest(url,"");
                BaiduToken resData = JSONArray.parseObject(result, BaiduToken.class);
                token= resData.getAccess_token();
                redisCache.setCacheObject(Constants.BAIDU_TOKEN, token, resData.getExpires_in(), TimeUnit.MILLISECONDS);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return token;
    }


    public String checkInfo(String userName,String idCard){
        RiderInfoService riderInfoService = ApplicationContexts.getBean(RiderInfoService.class);
        RiderInfo riderInfo = riderInfoService.getOne(Wrappers.<RiderInfo>lambdaQuery().eq(RiderInfo::getIdCard, idCard));
        // if(ObjectUtils.isNotEmpty(riderInfo))return "该身份证已注册";
        String token = getToken();
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/person/idmatch?access_token="+token;
        try {
            String result = OkhttpUtil.doPostFormData(url,idCard,userName);
            BaiduResult resData = JSONArray.parseObject(result, BaiduResult.class);
            if(resData.getError_code()!=0)return "姓名和身份证号码不匹配";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 骑手数据转 InfoView
     * @param car 车俩信息
     * @return 转换数据
     */
    public RiderInfoView rider2RiderInfoView(RiderInfoCar car){
        RiderInfoView riderInfoView = new RiderInfoView();
        RiderInfoService riderInfoService = ApplicationContexts.getBean(RiderInfoService.class);
        RiderCompanyService riderCompanyService = ApplicationContexts.getBean(RiderCompanyService.class);

        RiderInfo riderInfo = riderInfoService.getById(car.getRiderId());
        Optional.ofNullable(riderInfo).ifPresent(v->{
            RiderCompany riderCompany = riderCompanyService.getById(riderInfo.getPlatformCompanyId());
            riderInfoView.setXm(v.getName());
            riderInfoView.setSfzmhm(v.getIdCard());
            riderInfoView.setWmqy(riderCompany.getName());
            riderInfoView.setQybm(riderInfo.getPlatformCompanyId());
            riderInfoView.setGxbs(riderInfo.getAuditStatus()==0?OperateEnum.add.getValue():OperateEnum.update.getValue());
            riderInfoView.setSjly("1");
            riderInfoView.setRyid(car.getRiderId());
            riderInfoView.setHphm(car.getLicensePlateNumber());
            riderInfoView.setFzjg(car.getAgencies());
            riderInfoView.setSyr(car.getOwner());
            riderInfoView.setSfzmhm(riderInfo.getIdCard());
            riderInfoView.setClsbdm(car.getDiscernNo());
            riderInfoView.setClid(car.getId());
            riderInfoView.setSyrsfzmhm(riderInfo.getIdCard());
        });
        return riderInfoView;
    }

    /**
     * 检查骑手基本信息
     * @param car
     * @return 检查结果
     */
    public String checkBaseInfo(RiderInfoCar car){
        if(StringUtils.isEmpty(car.getRiderId())){
            return "骑手id不能为空";
        }
        if(StringUtils.isEmpty(car.getLicensePlateNumber())){
            return "车牌号码不能为空";
        }
        if(StringUtils.isEmpty(car.getDiscernNo())){
            return "车俩识别代码不能为空";
        }
        if(StringUtils.isEmpty(car.getOwner())){
            return "车主姓名不能为空";
        }
        return "";
    }
}
